﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using NetFtp.Core.Login;

namespace NetFtp.Core.DAO
{
    public class UserAccess
    {
        private DataSetTableAdapters.UserTableAdapter connexion;
        private DataSet cache;
        private IList<User> users;

        public UserAccess()
        {
            users = new List<User>();
            cache = new DataSet();
            connexion = new DataSetTableAdapters.UserTableAdapter();
            connexion.Fill(cache.User);

            foreach (DataSet.UserRow row in cache.User.Rows)
            {
                this.users.Add(new User(row.userId, row.username, row.password));
            }
        }

        public IList<User>liste
        {
            get
            {
                return this.users;
            }
        }

        /// <summary>
        /// Sauve an bdd l'utilisateur.
        /// </summary>
        /// <param name="user"></param>
        public void doSave(User user)
        {
            cache.User.AddUserRow(user.Username, user.Password);
            connexion.Update(cache);
            connexion.Fill(cache.User);

            users.Clear();
            foreach (DataSet.UserRow row in cache.User.Rows)
            {
                this.users.Add(new User(row.username, row.password));
            }
        }

        /// <summary>
        /// Hydrate l'utilisateur existant.
        /// </summary>
        /// <param name="user"></param>
        public void doUpdate(User user, string newpassword)
        {
            foreach (DataSet.UserRow row in cache.User.Rows)
            {
                if (row.username == user.Username)
                {
                    row.password = newpassword;
                }
            }
            connexion.Update(cache);
        }
    }
}
